from django import template 
from django.template import resolve_variable
from links.models import Blogroll, Link


register = template.Library()

"""List of templates that will help to use the links application:
        
   Usae:     
        {% get_blogroll as blogs %} list all the active blogs defined
        {% get_links as links    %} lists all the active links defined
    
    """

    
@register.tag('get_blogroll')
def do_get_blogroll(parser, token):
    ''' get_blogroll as blog_list'''
    bits = token.contents.split()
    if len(bits) == 3 and bits[1] == 'as':
        return BlogrollNode(bits[2])
    else:
        return template.TemplateSyntaxError

class BlogrollNode(template.Node):
    def __init__(self, context_variable):
        self.context_variable = context_variable

    def render(self, context):
        blog_list = Blogroll.objects.current_active().order_by('name')
        context[self.context_variable] = blog_list
        return ''

@register.tag('get_links')
def do_get_links(parser, token):
    ''' get_links as link_list'''    
    bits = token.contents.split()
    if len(bits) == 3 and bits[1] == 'as':
        return LinkNode(bits[2])
    else:
        return template.TemplateSyntaxError

class LinkNode(template.Node):
    def __init__(self, context_variable):
        self.context_variable = context_variable

    def render(self, context):
        link_list = Link.objects.current_active().order_by('name')
        context[self.context_variable] = link_list
        return ''
